﻿using AutoMapper;
using MediatR;
using S.Services.SheepMale.Api.Application.Command.SheepMaleCommand;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;

namespace S.Services.SheepMale.Api.Application.CommandHandler.SheepMaleCommandHandler
{
    public class SheepFatherUpdCommandHandler : IRequestHandler<SheepFatherUpdCommand, int>
    {
        private readonly IMapper mapper;

        private readonly IRepository<SheepMaleInfo> repository;

        public SheepFatherUpdCommandHandler(IMapper mapper, IRepository<SheepMaleInfo> repository)
        {
            this.mapper = mapper;
            this.repository = repository;
        }

        public async Task<int> Handle(SheepFatherUpdCommand request, CancellationToken cancellationToken)
        {
            var result = repository.AllAsync().Result.Where(x => x.Earbugles == request.Earbugles && x.MaleId != request.MaleId);
            if (result.Count() != 0)
            {
                return -1;
            }
            request.UpdateDate = DateTime.Now;
            return await repository.UpdateAsync(mapper.Map<SheepMaleInfo>(request));
        }
    }
}
